<template>
  <el-dialog :model-value="showAddVideoVisible" :title="props.editInfo.id ? '编辑视频' : '新增视频'" width="700"
    :close-on-click-modal="false" @close="resetForm">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="视频标题" prop="questionName">
        <el-input v-model="ruleForm.questionName" type="textarea" :rows="2" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="视频描述" prop="answer">
        <el-input v-model="ruleForm.answer" type="textarea" :rows="5" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="视频封面" prop="img">
        <el-input v-model="ruleForm.questionImg" style="display: none"></el-input>
        <div class="avatar-uploader" @click="showImageChooseDialog = true">
          <el-image v-if="questionLogo" :src="questionLogo" class="avatar" fit="contain"></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
              <Plus />
            </el-icon></i>
          <div v-if="questionLogo" class="mask">替换</div>
          <el-icon v-if="questionLogo" class="del-image" :size="20" @click.stop="handleDelImg">
            <CircleCloseFilled />
          </el-icon>
        </div>
      </el-form-item>

      <el-form-item label="视频课程" prop="videoUrl">
        <el-input v-model="ruleForm.videoUrl">
          <template #append>
            <!-- <el-upload class="video-uploader" :action="server" :headers="imgheaders" :show-file-list="false"
              :on-error="handleError" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
              accept="video/*">
              <el-button style="color: #2b8dfa" type="primary">点击上传</el-button>
            </el-upload> -->
            <div class="video-uploader" @click="showVideoChooseDialog = true">
              <el-button style="color: #2b8dfa" type="primary">选择视频</el-button>
            </div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="用户权限" prop="isPay">
        <div>
          <el-radio-group v-model="ruleForm.isPay">
            <el-radio value="0">全部用户可看</el-radio>
            <el-radio value="1">仅限VIP会员可看</el-radio>
          </el-radio-group>
          <div style="color: #ccc;font-size: 12px;">选择“仅限VIP会员可看”时请先设置好会员权益</div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)">确认</el-button>
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
    :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
    :operationType="false"></image-selected-dialog>
  <video-group-dialog v-if="showVideoChooseDialog" :show-video-choose-dialog="showVideoChooseDialog"
    :single-type="singleType" :operation-type="false" @close-dialog="handleCloseVideoDialog" />
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { getcarmodellist, addVideoData, putquestioncategory } from '@/api/questionbank'
import { Plus } from '@element-plus/icons-vue'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import VideoGroupDialog from '@/views/decoration/diyComponents/VideoGroupDialog.vue'

const userStore = useUserStore()

const props = defineProps({
  showAddVideoVisible: {
    type: Boolean
  },
  editInfo: {
    type: Object,
    default: () => {
      return {
        id: ''
      }
    }
  },
  groupInfo: {
    type: Object,
    default: () => {
      return {
        id: ''
      }
    }
  },
  groupId: {
    type: [String, Number],
    default: ''
  }
})

const emit = defineEmits(['closeDialog'])

let server = `${import.meta.env.VITE_API_URL}files`
let { accessToken } = userStore
const imgheaders = { Authorization: 'Bearer ' + accessToken }
const questionLogo = ref('')
const editLoading = ref(false)
const carList = ref<Array<carLists>>([])
interface carLists {
  label: string
  value: string
  tag: string
}
interface RuleForm {
  sort: string
  questionName: string
  videoUrl: string
  answer: string
  isPay: string
  questionImg?: string
  carIds: string
}

const ruleFormRef = ref<FormInstance>()
let loadingMessage: ReturnType<typeof ElMessage> | null = null

const ruleForm = reactive<RuleForm>({
  sort: '1',
  questionName: '',
  answer: '',
  videoUrl: '',
  isPay: '1',
  questionImg: '',
  carIds: ''
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const singleType = ref(true)
const showVideoChooseDialog = ref(false)
const handleCloseImageDialog = (value: any) => {
  if (value && value.fileUrl) { questionLogo.value = value.fileUrl }
  showImageChooseDialog.value = false
}
const handleCloseVideoDialog = (value: any) => {
  if (value && value.fileUrl) { ruleForm.videoUrl = value.fileUrl }
  showVideoChooseDialog.value = false
}

const handleDelImg = () => {
  questionLogo.value = ''
}

const rules = reactive<FormRules<RuleForm>>({
  sort: [{ required: true, message: '不能为空', trigger: 'blur' }],
  questionName: [{ required: true, message: '不能为空', trigger: 'blur' }],
  // answer: [{ required: true, message: '不能为空', trigger: 'blur' }],
  videoUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
  isPay: [{ required: true, message: '不能为空', trigger: 'change' }]
})


const handleAvatarSuccess = (file: any) => {
  ruleForm.videoUrl = file.data.url

  loadingMessage?.close()
  ElMessage({
    showClose: true,
    message: '视频上传成功！',
    type: 'success'
  })
}
//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
  loadingMessage = ElMessage({
    message: '视频上传中，请稍后...',
    type: 'info',
    duration: 0,
    showClose: false
  })

  const isVideo = file.type.startsWith('video/')
  const isLt100M = file.size / 1024 / 1024 < 100
  if (!isVideo) {
    ElMessage.error('只能上传视频文件')
    loadingMessage?.close()
    return false
  }
  if (!isLt100M) {
    ElMessage.error('视频大小不能超过 100MB')
    loadingMessage?.close()
    return false
  }

  return true
}

const handleError = () => {
  loadingMessage?.close()
  ElMessage({
    showClose: true,
    message: '上传失败，请稍后重试',
    type: 'error'
  })
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (props.editInfo.id) {
        handleEdit()
      } else {
        handleAdd()
      }
    } else {
    }
  })
}

async function handleAdd() {
  try {
    editLoading.value = true
    ruleForm.questionImg = questionLogo.value
    const res = await addVideoData({
      ...ruleForm,
      groupIds: props.groupInfo.id
    })
    if (res.code === '00000') {
      emit('closeDialog', true)
      ElMessage.success('新增成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

async function handleEdit() {
  try {
    editLoading.value = true
    ruleForm.questionImg = questionLogo.value
    const res = await putquestioncategory.putquestioncategoryId(props.editInfo.id, {
      ...ruleForm,
      groupId: props.groupId
    })
    if (res.code === '00000') {
      emit('closeDialog', true)
      ElMessage.success('编辑成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

//车型下拉接口
const getcarmodellistinfo = async () => {
  let obj = {}
  const res = await getcarmodellist.getcarmodelId(obj)
  if (res.code == 0) {
    carList.value = res.data
  }
}

const resetForm = () => {
  emit('closeDialog')
}
onMounted(() => {
  if (props.editInfo.id) {
    ruleForm.sort = props.editInfo.sort
    ruleForm.isPay = String(props.editInfo.isPay)
    ruleForm.questionName = props.editInfo.questionName
    ruleForm.videoUrl = props.editInfo.videoUrl
    ruleForm.answer = props.editInfo.answer
    ruleForm.videoUrl = props.editInfo.videoUrl
    ruleForm.questionImg = props.editInfo.questionImg
    questionLogo.value = props.editInfo.questionImg
  }
  ruleForm.carIds = props.groupInfo.carIds
  getcarmodellistinfo()
})
</script>

<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
